package 生产者_消费者;


import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author:谢君臣
 * @Date:2021/10/21-18:52
 * @version:1.0
 * @function:
 */
public class factory {
    private volatile Queue<Integer> queue = new ArrayDeque();
    volatile int state = 0;
    private int n;
    private Lock lock = new ReentrantLock();
    private Thread product = new Thread(new Product(), "生产者");
    private Thread consumer = new Thread(new Consumer(), "消费者");
    Condition p = lock.newCondition();
    Condition c = lock.newCondition();

    public factory(int n) {
        this.n = n;
        state = 1;
    }

    public void start() {
        product.start();
        consumer.start();

    }

    class Product implements Runnable {
        @Override
        public void run() {
            lock.lock();
            try {
                int i = 0;
                while (i < n) {
                    queue.add(++i);
                    System.out.println(Thread.currentThread().getName() + ":生产+1 ：" + i);
                    c.signal();
                    p.await();
                }
                state = 0;
                c.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    class Consumer implements Runnable {
        @Override
        public void run() {
            lock.lock();
            try {
                while (state != 0) {
                    if (!queue.isEmpty())
                        System.out.println(Thread.currentThread().getName() + "消费：" + queue.poll());
                    p.signal();
                    c.await();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

        }
    }

    public static void main(String[] args) throws InterruptedException {
        factory solution = new factory(100);
        solution.start();
        TimeUnit.SECONDS.sleep(2);
    }

}
